package com.zklh.leetcode.interviewTop150;

import java.util.Arrays;

/**
 * 除以自身以外数组的乘积
 *
 * @Author tongnan
 * @Date 2024/6/7
 * @Version 1.0
 */
public class Solution238 {
    public int[] productExceptSelf(int[] nums) {
        // 存储返回结果, 临时被用作存储前置乘积的容器
        int[] result = new int[nums.length];
        result[nums.length-1] = 1;
        for (int i = nums.length - 2; i >= 0; i--) {
            result[i] = nums[i+1] * result[i + 1];
        }
        int prevNum = nums[0];
        nums[0] = 1;
        for (int i = 1; i < nums.length; i++) {
            int tempNum = nums[i];
            nums[i] = prevNum * nums[i - 1];
            prevNum = tempNum;
        }

        for (int i = 0; i < nums.length; i++) {
            result[i] = nums[i] * result[i];
        }
        return result;
    }

    public static void main(String[] args) {
        Solution238 solution238 = new Solution238();
        int[] nums = {1,2,3,4};
        int[] nums2 = {-1,1,0,-3,3};
        System.out.println(Arrays.toString(solution238.productExceptSelf(nums)));
        System.out.println(Arrays.toString(solution238.productExceptSelf(nums2)));
    }
}